package v1

import (
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/xuri/excelize/v2"
	"go.uber.org/zap"
	"maya-service/bll"
	log "maya-service/collector/logger"
	"maya-service/config"
	"maya-service/model"
	"maya-service/model/po"
	mallPo "maya-service/model/po/mall"
	"maya-service/server/web/middleware"
	"maya-service/utils"
	"maya-service/utils/request"
	"os"
)

var AiQuestion = &aiQuestion{}

func init() {
	RegisterRouter(AiQuestion)
}

type aiQuestion struct{}

// Init
func (a *aiQuestion) Init(r *gin.RouterGroup) {
	g := r.Group("/aiQuestion", middleware.Auth())
	{
		g.POST("/create", a.create)
		g.POST("/batchDelete", a.batchDelete)
		g.POST("/import", a.importExcel)
	}

	g1 := r.Group("/aiQuestion")
	{
		g1.POST("/update", a.update)
		g1.POST("/list", a.list)
		g1.POST("/delete", a.delete)
		g1.POST("/detail", a.find)
	}
}

func (a *aiQuestion) importExcel(c *gin.Context) {
	// 保存文件
	filePath, err := UploadFile(c)
	if err != nil {
		c.Error(err)
		return
	}

	defer func() {
		os.RemoveAll(filePath)
	}()

	// 读取数据
	var file *excelize.File
	defer func() {
		if err = file.Close(); err != nil {
			log.Error("")
		}
	}()

	// 读取表格内容
	if file, err = excelize.OpenFile(filePath); err != nil {
		c.Error(fmt.Errorf("文件解析失败"))
		return
	}

	sheets := file.GetSheetMap()

	// 获取工作表中指定单元格的值
	for i := 1; i <= len(sheets); i++ {
		rows, err := file.GetRows(sheets[i])
		if err != nil {
			c.Error(fmt.Errorf("excel 格式解析错误"))
			return
		}

		for index, row := range rows {
			if index == 0 {
				continue
			}

			if GetData(row, 0) == "" {
				continue
			}

			// 插入问题
			_, err = bll.AiQuestion.Create(c.Request.Context(), &model.AiQuestionCreateRequest{
				Topic:           GetData(row, 0),
				Content:         GetData(row, 1),
				ReferenceAnswer: GetData(row, 2),
				Level:           int(StrToInt64(GetData(row, 3))),
				Module:          int(StrToInt64(GetData(row, 4))),
				GuideWords:      GetData(row, 5),
				Background:      GetData(row, 6),
				GuideAnswer:     GetData(row, 7),
				Questioner:      GetData(row, 8),
			})
		}
	}

	go func() {
		defer utils.ExceptionCatch()
		bll.AiQuestion.RefreshGuideAnswer()
	}()
	utils.ResponseOk(c, nil)
	return

}
func (a *aiQuestion) batchDelete(c *gin.Context) {
	var (
		in  = &po.BatchDeleteAiQuestionReq{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	// 根据模块批量删除
	if in.ModuleId > 0 {
		err = bll.AiQuestion.Delete(c.Request.Context(), &model.AiQuestionDeleteRequest{
			ModuleId: int(in.ModuleId),
		})
		if err != nil {
			c.Error(err)
			return
		}
		utils.ResponseOk(c, nil)
		return
	}

	if len(in.QuestionIds) > 0 {
		for i := 0; i < len(in.QuestionIds); i++ {
			questionRet, err := bll.AiQuestion.Find(context.Background(), &model.AiQuestionInfoRequest{
				Id: in.QuestionIds[i],
			})

			if questionRet != nil && questionRet.Id <= 0 {
				if questionRet.CourseType > 0 {
					findResult, _ := bll.GoodsCollector.Find(context.Background(), &model.GoodsCollectorInfoRequest{
						Id: questionRet.CollectorId,
					})
					if findResult == nil || findResult.Id <= 0 {
						return
					}

					if questionRet.ProductId > 0 {
						dto := mallPo.ProductOpenDTO{
							ThirdProductId: fmt.Sprintf("%v", in.QuestionIds[i]),
							ProductId:      questionRet.ProductId,
							ProductName:    questionRet.Topic,
							ProductPrice:   fmt.Sprintf("%v", questionRet.Price),
							ProductStock:   questionRet.Stock,
							State:          2,
						}
						// 创建商品
						_, err = request.CreateOrUpdateProduct(c.GetHeader("Authorization"), config.Conf.Env, mallPo.CreateProductRequest{
							GoodsId: findResult.ThirdGoodsId,
							ProductList: []mallPo.ProductOpenDTO{
								dto,
							},
						})
						if err != nil {
							log.Info(" 删除题目 更新商品下架失败 ", zap.Any("dto", dto))
						}
					}
				}
			}
		}

		err = bll.AiQuestion.Delete(c.Request.Context(), &model.AiQuestionDeleteRequest{
			Ids: in.QuestionIds,
		})
		if err != nil {
			c.Error(err)
			return
		}

		utils.ResponseOk(c, nil)
		return
	}

	utils.ResponseOk(c, nil)
}

// create
func (a *aiQuestion) create(c *gin.Context) {
	var (
		in  = &model.AiQuestionCreateRequest{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	if _, err = bll.AiQuestion.Create(c.Request.Context(), in); err != nil {
		c.Error(err)
		return
	}
	utils.ResponseOk(c, nil)
}

// update
func (a *aiQuestion) update(c *gin.Context) {
	var (
		in  = &model.AiQuestionUpdateRequest{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	if err = bll.AiQuestion.Update(c.Request.Context(), in); err != nil {
		c.Error(err)
		return
	}
	utils.ResponseOk(c, nil)
}

// list
func (a *aiQuestion) list(c *gin.Context) {
	var (
		in  = &model.AiQuestionListRequest{}
		out = &model.AiQuestionListResponse{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	if out, err = bll.AiQuestion.List(c.Request.Context(), in); err != nil {
		c.Error(err)
		return
	}
	utils.ResponseOk(c, out)
}

// list
func (a *aiQuestion) find(c *gin.Context) {
	var (
		in  = &model.AiQuestionInfoRequest{}
		out = &model.AiQuestionInfo{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	if out, err = bll.AiQuestion.Find(c.Request.Context(), in); err != nil {
		c.Error(err)
		return
	}
	utils.ResponseOk(c, out)
}

// delete
func (a *aiQuestion) delete(c *gin.Context) {
	var (
		in  = &model.AiQuestionDeleteRequest{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	if err = bll.AiQuestion.Delete(c.Request.Context(), in); err != nil {
		c.Error(err)
		return
	}

	go func() {
		defer utils.ExceptionCatch()
		questionRet, _ := bll.AiQuestion.Find(c.Request.Context(), &model.AiQuestionInfoRequest{
			Id: in.Id,
		})

		if questionRet == nil || questionRet.Id <= 0 {
			return
		}
		findResult, _ := bll.GoodsCollector.Find(c.Request.Context(), &model.GoodsCollectorInfoRequest{
			Id: questionRet.CollectorId,
		})
		if findResult == nil || findResult.Id <= 0 {
			return
		}

		dto := mallPo.ProductOpenDTO{
			ThirdProductId: fmt.Sprintf("%v", in.Id),
			State:          2,
		}
		// 创建商品
		_, err = request.CreateOrUpdateProduct(c.GetHeader("Authorization"), config.Conf.Env, mallPo.CreateProductRequest{
			GoodsId: findResult.ThirdGoodsId,
			ProductList: []mallPo.ProductOpenDTO{
				dto,
			},
		})
		if err != nil {
			log.Info(" 删除题目 更新商品下架失败 ", zap.Any("dto", dto))
		}
	}()
	utils.ResponseOk(c, nil)
}
